package com.xyb.service;

import com.xyb.utils.RandomUtils;
import com.xyb.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RegisterService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    public boolean sendRegCode(String iphoneNo) {
        int regCode = RandomUtils.getRandomInt(1000, 9999);                         //随机验证码
        //发送短信验证码
        try {
            SMSUtils.sendRegCode(iphoneNo, regCode);
        } catch (Exception e) {
            log.error("iphoneNo:" + iphoneNo + "-code:" + regCode + "短信发送失败!");
        }
        //redis 缓存
        String key = "verCode:reg:" + iphoneNo;                                        //redis Key
        redisTemplate.opsForValue().set(key, regCode, 5, TimeUnit.MINUTES);        // 5分钟有效
        return true;
    }

    public boolean selectRegisterCodeByIphoneNo(String iphoneNo, Integer code) {
        String key = "verCode:reg:" + iphoneNo;
        Integer obj = (Integer) redisTemplate.opsForValue().get(key);
        if (obj != null && obj.intValue() == code.intValue()) {
            return true;
        }
        return false;
    }
}
